package day11.CRUD;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import java.sql.ResultSet;

public class Demo6 {

    /**
     * 模似转帐

     create table account(
     id int primary key auto_increment,
     name varchar(40),
     money float
     )character set utf8 collate utf8_general_ci;
     insert into account(name,money) values('aaa',1000);
     insert into account(name,money) values('bbb',1000);
     insert into account(name,money) values('ccc',1000);

     */
    public static void main(String[] args) {

        Connection conn = null;
        PreparedStatement st = null;
        ResultSet rs = null;

        try{
            conn = JdbcUtils.getConnection();
            conn.setAutoCommit(false);   //start transaction，开启事务

            String sql1 = "update account set money=money-100 where name='aaa'";
            st = (PreparedStatement) conn.prepareStatement(sql1);
            st.executeUpdate();


            String sql2 = "update account set money=money+100 where name='bbb'";
            st = (PreparedStatement) conn.prepareStatement(sql2);
            st.executeUpdate();


            conn.commit();//提交

            System.out.println("成功！！！");  //log4j

        }catch (Exception e) {
            e.printStackTrace();//如果程序出错手动回滚
        }finally{
            JdbcUtils.release(conn, st, rs);
        }

    }

}
